package data_daos

import (
	"errors"
	"gorm.io/gorm"
	"log"
	"rabbit_love/src/model"
	"rabbit_love/src/service/client/forms/request/data_forms"
	"rabbit_love/src/service/client/utils"
)

func GetMarkListDao(loverId int) ([]map[string]interface{}, error) {
	var (
		clientDB = utils.ClientDB
		data     []map[string]interface{}
		err      error
	)

	err = clientDB.Transaction(func(tx *gorm.DB) error {
		if err = clientDB.Model(&model.AnniversaryTable{}).Select("`id`,`occurrenceDate`, `name`, `data`, `read`").Where("loverRelationId = ?", loverId).Order("occurrenceDate desc").Find(&data).Error; err != nil {
			return err
		}
		if err = clientDB.Model(&model.AnniversaryTable{}).Where("loverRelationId = ?", loverId).Update("`read`", true).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		log.Println("GetMarkListDao Err: ", err.Error())
		return nil, errors.New("获取失败")
	}

	return data, nil
}

func AddMarkListDao(userId, loverId int, form *data_forms.AddMarkRequest) error {
	var (
		clientDB = utils.ClientDB
		err      error
	)

	data := &model.AnniversaryTable{
		UserTableId:          int64(userId),
		LoverRelationTableId: int64(loverId),
		Name:                 form.Name,
		Data:                 form.Data,
		OccurrenceDate:       form.OccurrenceDate.Time,
	}
	if err = clientDB.Create(&data).Error; err != nil {
		log.Println("AddMarkListDao Err: ", err.Error())
		return errors.New("新增数据失败")
	}
	return nil
}

func UpdMarkListDao(userId, loverId int, form *data_forms.UpdMarkRequest) error {
	var (
		clientDB = utils.ClientDB
		err      error
	)

	if err = clientDB.Model(&model.AnniversaryTable{}).
		Where("id = ? and loverRelationId = ? and userId = ?", form.MarkId, loverId, userId).
		Updates(&model.AnniversaryTable{
			OccurrenceDate: form.OccurrenceDate.Time,
			Name:           form.Name,
			Data:           form.Data,
			Read:           false,
		}).Error; err != nil {
		log.Println("UpdMarkListDao Err: ", err.Error())
		return errors.New("更新失败")
	}
	return nil
}

func DelMarkListDao(userId, loverId, markId int) error {
	var (
		clientDB = utils.ClientDB
		err      error
	)

	if err = clientDB.Model(&model.AnniversaryTable{}).
		Where("id = ? and loverRelationId = ? and userId = ?", markId, loverId, userId).Delete(&model.AnniversaryTable{}).Error; err != nil {
		log.Println("DelMarkListDao Err: ", err.Error())
		return errors.New("操作失败")
	}
	return nil
}
